import router from './router';
import store from './store';
import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import {
    getToken
    // getCookie
} from '@/utils/auth'; // get token from cookie
import { Route } from 'vue-router';
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login']; // no redirect whitelist
const REPORT_TYPE = 4;
function isEmpty(s) {
    return s === undefined || s === null || s === '';
}
function needExtraRedirect(to, from) {
    const toId = to.meta.baseModuleId;
    const fromId = from.meta.baseModuleId;
    return !isEmpty(toId) && !isEmpty(fromId) && toId === fromId;
}
function isReportWithRedirect(to, from) {
    const toType = to.meta.type;
    const fromType = from.meta.type;
    return toType === REPORT_TYPE && fromType === REPORT_TYPE;
}

router.beforeEach(async (to: Route, from: Route, next: any) => {
    NProgress.start();
    const hasToken = getToken();
    // 这里存储多个 token 是为了支持 多用户去登陆
    // const userId = store.state.user.userId
    // const hasToken = getCookie(`${userId}_token`) || getCookie('tempToken')

    // console.log('routerBeforeEach  hasToken', hasToken)
    const permission_routers = store.state.permission.routers;

    window.document.title = 'RBP系统';

    if (hasToken) {
        if (to.path === '/login') {
            next({ path: '/' });
            NProgress.done();
        } else {
            // console.log('permission_routers', permission_routers)
            if (permission_routers.length) {
                // 同组件切换的时候 需要重定向一次
                if (needExtraRedirect(to, from) || isReportWithRedirect(to, from)) {
                    // console.log('执行了')
                    return next(`/redirect${to.fullPath}`);
                }
                next();
            } else {
                try {
                    await store.dispatch('user/getInfo');
                    // console.log('没路由 permission_routers', permission_routers)
                    store.dispatch('permission/GenerateRoutes').then((accessRoutes) => {
                        router.addRoutes(accessRoutes); // 动态添加可访问路由表
                        next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
                    });
                    await store.dispatch('app/LanguageTypeSetting');
                } catch (error) {
                    // console.log('routerBeforeEach  error', error)
                    await store.dispatch('user/resetToken');
                    Message.error(error.toString() || 'Has Error');
                    // this._message({ message: error.toString(), type: 'error'})
                    next({ path: '/' });
                    NProgress.done();
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next('/login');
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});
